import 'package:flutter/material.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/game/game_detail/widgets/widget_round_ball.dart';

import 'package:flutter_09_game/pages/profile/profile_bet_record/models/model_game_round_join.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/utils/utils_time.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/widgets/image/image_view.dart';
import 'package:flutter_09_game/widgets/widget_user_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

/// 投注记录Item组件
/// 严格按照项目深色主题设计风格实现，参考deposit_record_commission组件
class WidgetBetRecordItem extends StatelessWidget {
  final ModelGameRoundJoinGameRoundJoin data;
  final bool isPage;

  const WidgetBetRecordItem(
      {super.key, required this.data, this.isPage = true});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w).copyWith(top: 16.w),
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: AppColor.navBgColor,
        borderRadius: BorderRadius.circular(12.w),
      ),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                  child: WidgetUserHeader(
                userAvatar: data.user?.avatar,
                isOnline: false,
                username: data.user?.username,
                memberCount: data.user?.memberCount,
                userIdentity: data.user?.identity,
                withdrawAddress: data.user?.withdrawAddress,
                showWithdrawAddress: true,
              )),
              12.horizontalSpace,
              AutoImage(
                UtilsOther().getAmountTagIcon(data.symbol),
                width: 20.w,
              ),
              4.horizontalSpace,
              Text(
                data.symbol ?? '',
                style: TextStyle(
                  color: AppColor.textPrimary.withOpacity(0.7),
                  fontSize: 14.sp,
                ),
              )
            ],
          ),
          24.verticalSpaceFromWidth,
          // // 顶部游戏信息和状态
          // _buildTopSection(),
          // 16.verticalSpaceFromWidth,
          // // 中间投注信息
          _buildBetSection(),
          24.verticalSpaceFromWidth,
          isPage ? _buildPage() : _buildGame()
        ],
      ),
    );
  }

  Widget _buildGame() {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
                child: _builtItems(LocaleKeys.winningStatus.tr,
                    child: Text(
                      data.isWin == true
                          ? LocaleKeys.winning.tr
                          : LocaleKeys.notWinning.tr,
                      style: TextStyle(
                        color: data.isWin == true
                            ? AppColor.homePrizePoolIndicator
                            : AppColor.gameResultEven,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ))),
            4.horizontalSpace,
            Expanded(
                child: _builtItems(LocaleKeys.betType.tr,
                    rightStr: LocaleKeys.gameBet.tr)),
          ],
        ),
        4.verticalSpaceFromWidth,
        _builtItems(LocaleKeys.participateGame.tr,
            rightStr: data.thirdGame?.gameName ?? ''),
        4.verticalSpaceFromWidth,
        _builtItems(LocaleKeys.betOrderNumber.tr,
            rightStr: data.transactionCode ?? '', showCopy: true),
        4.verticalSpaceFromWidth,
        _builtItems(
          LocaleKeys.betTime.tr,
          rightStr: UtilsTime.depositFormatTime(data.createdAt),
        ),
      ],
    );
  }

  Widget _buildPage() {
    // data.gameRound?.blockHash
    // String? hash = UtilsOther.getLastSixDigits('dakshd7777');
    // List<String> hashs = hash.split(data.gameRound?.result?.toString() ?? '');
    return Column(
      children: [
        Row(
          children: [
            Expanded(
                child: _builtItems(LocaleKeys.participateGame.tr,
                    rightStr: data.game?.name ?? '')),
            4.horizontalSpace,
            Expanded(
                child: _builtItems(LocaleKeys.betType.tr,
                    rightStr: data.joinType == 2
                        ? LocaleKeys.pageBet.tr
                        : LocaleKeys.transferBet.tr))
          ],
        ),
        4.verticalSpaceFromWidth,
        Row(
          children: [
            Expanded(
                child: _builtItems(LocaleKeys.winningStatus.tr,
                    child: data.status == 3
                        ? Text(
                            data.isWin == true
                                ? LocaleKeys.winning.tr
                                : LocaleKeys.notWinning.tr,
                            style: TextStyle(
                              color: data.isWin == true
                                  ? AppColor.homePrizePoolIndicator
                                  : AppColor.gameResultEven,
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          )
                        : Text(
                            LocaleKeys.notDrawn.tr,
                            style: TextStyle(
                              color: AppColor.textPrimary.withOpacity(0.7),
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ))),
            4.horizontalSpace,
            Expanded(
                child: _builtItems(LocaleKeys.betArea.tr,
                    child: WidgetRoundBall(
                      result: data.direction,
                      isBig: false,
                    ))),
          ],
        ),
        4.verticalSpaceFromWidth,
        _builtItems(LocaleKeys.betOrderNumber.tr,
            rightStr: data.identity ?? '', showCopy: true),
        4.verticalSpaceFromWidth,
        _builtItems(LocaleKeys.drawBlock.tr,
            rightStr: (data.gameRound?.round ?? '').toString(), showCopy: true),
        4.verticalSpaceFromWidth,
        _builtItems(
          LocaleKeys.blockHash.tr,
          child: data.status == 3
              ? Row(children: [
                  UtilsOther.buildHashDigitsViewString(
                      data.gameRound?.blockHash ?? '', data.gameRound?.result,
                      count: 10),
                  // Text.rich(TextSpan(
                  //         style: TextStyle(
                  //           fontSize: 12.sp,
                  //           fontWeight: FontWeight.w400,
                  //           color: AppColor.textPrimary.withOpacity(0.7),
                  //         ),
                  //         children: [
                  //           TextSpan(
                  //             text: hashs.first,
                  //           ),
                  //           TextSpan(
                  //             text: '${data.gameRound?.result ?? ''}',
                  //             style: TextStyle(
                  //               color: _getResultColor(data.gameRound?.result),
                  //             ),
                  //           ),
                  //           TextSpan(
                  //             text: hashs.last,
                  //           ),
                  //         ],
                  //       )),
                  4.horizontalSpace,
                  GestureDetector(
                      onTap: () {
                        UtilsOther.openVerify(data.round);
                      },
                      child: Text(
                        LocaleKeys.verify.tr, //   '验证',
                        style: TextStyle(
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400,
                          color: AppColor.primary,
                        ),
                      )),
                  4.horizontalSpace,
                  GestureDetector(
                    onTap: () {
                      UtilsOther.copyMemberId(data.gameRound?.blockHash ?? '');
                    },
                    child: AutoImage(
                      Assets.promotionCommissionCopy,
                      width: 16.w,
                    ),
                  ),
                ])
              : Text(
                  '--',
                  style: TextStyle(
                    color: AppColor.textPrimary.withOpacity(0.7),
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
        ),
        4.verticalSpaceFromWidth,
        _builtItems(
          LocaleKeys.betTime.tr,
          rightStr: UtilsTime.depositFormatTime(data.createdAt),
        ),
      ],
    );
  }

  /// 构建投注区域（金额和币种）
  Widget _buildBetSection() {
    // final winAmount = data.winAmount ?? 0;

    return Row(
      children: [
        // 左侧：投注信息
        Expanded(
          child: Column(
            // crossAxisAlignment: CrossAxisAlignment.c,
            children: [
              // 投注金额
              Text(
                LocaleKeys.stakeAmount.tr,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: AppColor.textPrimary.withOpacity(0.7),
                ),
              ),
              Text(
                data.amount?.formatWallet() ?? '',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w900,
                  color: AppColor.primary,
                ),
              ),
            ],
          ),
        ),

        8.horizontalSpace,

        Expanded(
          child: Column(
            // crossAxisAlignment: CrossAxisAlignment.c,
            children: [
              // 投注金额
              Text(
                LocaleKeys.returnAmount.tr,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: AppColor.textPrimary.withOpacity(0.7),
                ),
              ),

              _buildAmount(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildAmount() {
    // if (isPage) {
      final isWin = data.isWin ?? false;
      return data.status == 3 || isPage == false
          ? Text(
              isWin
                  ? "+${data.winAmount?.formatWallet()}"
                  : "-${data.amount?.formatWallet()}",
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.w900,
                color: isWin
                    ? AppColor.homePrizePoolIndicator
                    : AppColor.gameResultEven,
              ),
            )
          : Text(
              '--',
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.w900,
                color: AppColor.textPrimary.withOpacity(0.94),
              ),
            );
    // } else {
    //   int amount = (data.winAmount ?? 0) - (data.amount ?? 0);
    //   return Text(
    //       amount > 0
    //           ? "+${amount.formatWallet()}"
    //           : amount.formatWallet(),
    //       style: TextStyle(
    //         fontSize: 20.sp,
    //         fontWeight: FontWeight.w900,
    //         color: amount > 0
    //             ? AppColor.homePrizePoolIndicator
    //             : AppColor.gameResultEven,
    //       ));
    // }
  }

  Widget _builtItems(String title,
      {String? rightStr, bool? showCopy, Widget? child}) {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: AppColor.homeTabBackground,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
              color: AppColor.textPrimary.withOpacity(0.7),
              fontSize: 12.sp,
            ),
          ),
          12.horizontalSpace,
          const Spacer(),
          // Text(data)
          if (rightStr != null)
            Text(
              rightStr,
              style: TextStyle(
                color: AppColor.textPrimary.withOpacity(0.94),
                fontSize: 12.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          if (showCopy != null)
            GestureDetector(
              onTap: () {
                UtilsOther.copyMemberId(rightStr ?? '');
              },
              child: AutoImage(
                Assets.promotionCommissionCopy,
                width: 16.w,
              ),
            ).marginOnly(left: 4.w),
          if (child != null) child
          // Expanded(child: )
        ],
      ),
    );
  }
}
